<template>
  <div id="app_login">

    <Row>
      <i-col span="24" class="header">
        <span > {{$site.siteName }}管理后台 </span>
        <Tag style="font-size:12px;color: #fff" >V{{version}}</Tag>
      </i-col>
    </Row>


    <Row style="margin: 2rem; justify-content: center;    display: flex;">
      <i-col :xs="{ span: 22, offset: 0 }" :sm="{ span: 8, offset:0 }" style="max-width: 350px">
        <Input v-model.trim="username" icon="ios-person" size="large"
               placeholder="用户名" />
        <Input v-model.trim='password' icon="ios-lock" type="password" size="large"
               placeholder="密码" style="padding-top: 30px"  @on-enter="Alogin"/>

        <div style="margin-top: 1rem;text-align: left;display: flex;align-items: center;
        justify-content: space-between" >
          <Checkbox v-model="isAutoLogin" disabled>暂不支持自动登录</Checkbox>
          <Button type="text" size="small"
                  @click="Areset" >全部重置
          </Button>
        </div>


        <Button type="primary" size="large" style="margin-top: 2rem;width: 100%"
                @click="Alogin" :loading="isLogining" v-show="!isNeedAskFor" > 立即登录
        </Button>

        <p style="font-size: 12px;margin-top: 2rem">
          <A  href="https://shimo.im/docs/473QylJOWBF5eP3w/" target="_blank" type="text" >历史更新日志</A>
        </p>


        <Button type="error" class="login_width" size="large"
                v-clipboard:copy="borwerInfo"
                　　v-clipboard:success="onCopy"
                　　v-clipboard:error="onError"
                style="margin-top: 3rem" v-show="isNeedAskFor" > {{askButtonTitle}}
        </Button>
        <Alert v-show="isNeedAskFor" type="error" style="margin-top: 2rem">您当前电脑或浏览器的授权许可不存在或者已经过期，请联系您的主管更新授权。</Alert>


        <validateCodeView @validateCodeEnd="validateCodeEnd" :phoneNum="phoneNum" :userId="userId" ref="AProductAddEdit"></validateCodeView>

      </i-col>

    </Row>



  </div>


</template>

<!--javascript 代码-->
<script>
  import ICol from "../../node_modules/view-design/src/components/grid/col";
  import validator from 'validator';
  import md5 from '../assets/js/md5.js'
  import Fingerprint2 from 'fingerprintjs2'
  //简单 aes加密
  import SimpleCrypto from "simple-crypto-js";
  import MTypes from "../store/types/TypesMutation"
  import ATypes from "../store/types/TypesAction"

  import ValidateCodeView from "./widgets/ValidateCodeView"
  import {getProductCommonData} from "./js/commonUtils"

  export default {
    components: {ICol, ValidateCodeView},
    data(){
      return {
        total:60,
        username: '',
        password: '',
        phoneNum:"",
        userId:"",
        isLogining: false,
        version: '3.9.5',
        isAutoLogin:this.$store.getters.isAutoLogin,
        borwerInfo :"",
        borwerFinger:"",
        borwerName:"",
        isNeedAskFor: false,
        askButtonTitle: "点击按钮可复制授权信息"

      }
    },
    methods: {
      Alogin(){
        this.$store.commit(MTypes.user.autoLogin,this.isAutoLogin);
        if (validator.isEmpty(this.username) || validator.isEmpty(this.password)) {
          this.$Message.error('您的用户名和密码不能为空');
        } else {
          this.validateCodeEnd(true);
          //this.loginNow();
        }
      },
      Areset(){
        this.username = '';
        this.password = ''
      },
      validateCodeEnd(isValidate){
        this.isLogining = true;
        let self = this;
        if(isValidate){
          this.$apiMain.login({
            'username': this.username,
            "password": md5(this.password.trim()),
            borwerFinger:this.borwerFinger,
            borwerName:this.borwerName})
            .then(function (response) {
              this.isLogining = false;
              if (response.success) {
                this.loginSuss(response,self);
                //重置需要提交指纹的标记
                // self.$store.commit(MTypes.local.storeIsNeedFinger, false);
              } else {
                  this.isNeedAskFor = this.$store.getters.isNeedFinger;
                  if (!this.isNeedAskFor){
                    this.$Message.error(response.errorMessage);
                  }
              }
            }.bind(this))
            .catch(function (error) {
              this.$Message.error('登录失败,请您重新尝试!');
              console.log(error);
              this.isLogining = false
            }.bind(this))
        }
      },
      loginNow(){
        this.isLogining = true;
        let self = this;
        this.$apiMain.loginUnVerify({'username': this.username,
          "password": md5(this.password.trim()),
          borwerFinger:this.borwerFinger,
          borwerName:this.borwerName
        })
          .then(function (response) {
            this.isLogining = false;
            if (response.success) {
                let userInfo = response.result.userInfo;
              if(userInfo.id == 'admin'){
                self.validateCodeEnd(true)
              }else if(null == userInfo.phone || "" == userInfo.phone){
                  self.$Modal.warning({
                    title:"确认",
                    content:"您的帐号还没有绑定手机号,请联系管理员"
                  });
              }else {
                  self.phoneNum = userInfo.phone;
                  self.userId = userInfo.id;
                  ValidateCodeView.methods.showModal();
              }
            } else {
              this.$Message.error(response.errorMessage);
            }

          }.bind(this))
          .catch(function (error) {
            this.$Message.error(error + '登录失败,请您重新尝试!');
            console.log(error);
            this.isLogining = false
          }.bind(this))

      },
      loginSuss(response,self){
        if (!response.result.userInfo.hasRole &&response.result.userInfo.userName!='admin' ) {
          self.$Message.error("当前账户尚未分配权限,禁止登陆管理后台,请您联系管理员.");
          return;
        }
        //登录成功去请求一些公共数据
        //this.$store.state.userInfo = response.result;
        //this.$store.state.actions.incrementAsync(response.result);
        self.$store.commit(MTypes.user.storeUserInfo, response.result.userInfo);
        self.$store.commit(MTypes.role.getAuths, response.result.authRules);

        setTimeout(function () {//延迟1秒 等userinfo存好后再去获取
          // self.$store.dispatch(ATypes.role.queryRoleInfo,response.result.roleUser);
          self.$store.commit(MTypes.base.storeImgPrefix, response.result.yunPath);
          self.$store.commit(MTypes.base.webDomain, response.result.webDomain);
          self.$store.commit(MTypes.base.siteEmail, response.result.siteEmail);
          self.$store.commit(MTypes.base.sendName, response.result.sendName);
          self.$store.commit(MTypes.base.aliImgPrefix, response.result.aliYunPath);
          self.$store.commit(MTypes.base.siteInfo, response.result.siteInfo);
          self.$store.commit(MTypes.order.orderStateEnum, response.result.orderStateEnum);
          self.$store.commit(MTypes.order.userStateEnum, response.result.userStateEnum);
          self.$store.commit(MTypes.order.shipStateEnum, response.result.shipStateEnum);
          self.$store.dispatch(ATypes.base.queryDictionaries);
            let types = [];
            types.push(3); //列表只查询分类
            getProductCommonData(self, null, types, true);
          self.$router.replace('/');
        }, 1000);
      },
      onCopy(e){
          this.askButtonTitle = "授权信息复制成功";

      },
      onError(e){
        this.askButtonTitle = "点击复制信息(复制失败)";
      },
      fingerAfter(components){
        var simpleCrypto = new SimpleCrypto(this.$tiyAesDey());
        // console.log("figerAfter")
        this.borwerName = components[0].value;
        this.borwerName = this.borwerName.replace(/\/[\d+][\.\d+]*/g,"");
        components[0].value = this.borwerName;
        var values = components.map(function (component) { return component.value });
        this.borwerFinger = Fingerprint2.x64hash128(values.join(this.$tiyAesDey()), 31);
        this.borwerInfo = simpleCrypto.encrypt(this.borwerName + "---" + this.borwerFinger);
        // console.log("---"+this.borwerFinger); // an array of components: {key: ..., value: ...}
        // console.log(components); // an array of components: {key: ..., value: ...}
        this.$store.commit(MTypes.local.storeBrowerFinger, this.borwerFinger);
      }

    },
    mounted(){ //如果已经登录，跳转到index页面
      if (false){
        let self = this;
        this.$apiMain.index().then(function (response) {
          if (response.success) {
            self.$router.push('/');
          }
        });
      }
    },
    created(){
      let self = this;
      //重置需要提交指纹的标记
      //self.$store.commit(MTypes.local.storeIsNeedFinger, false);
      var options = {
        excludes : {
          deviceMemory: true,
          webglVendorAndRenderer: true,
          //adBlock: true,
          enumerateDevices:true,
          availableScreenResolution: true
        }
      };
      if (window.requestIdleCallback) {
        requestIdleCallback(function () {
          Fingerprint2.get(options, function ( components) {
            self.fingerAfter(components)
          });
        })
      } else {
        setTimeout(function () {
          Fingerprint2.get(options ,function (components) {
            self.fingerAfter(components)
          })
        }, 500)
      }
    }
  }
</script>

<!--css样式-->
<style scoped="true" lang="less">
@import  (once,optional)  url("css/base.less");

  #app_login{
    //background: #2c3e50;
    height: 100vh;
    background-image: url("https://file.iviewui.com/admin-pro-dist/img/body.8aa7c4a6.svg") !important;
    background-repeat: no-repeat;
    background-position: 50%;
    background-size: 100%;

  }

  .header {
    color: @tiyWhite;
    text-align-all: center;
    font-size: 2.5em;
    padding: 40px;
    align-items: baseline;
    background:@tiyPrimaryColor;
  }


  .login_width{
    width: 28%;
  }

  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 30px;
    color: #c1c1c1;
    font-size: 10px;
  }


</style>
